<template>
  <div class="app-container rese_pwd_wrap">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>修改密码</span>
      </div>
      <el-form ref="pwdform" :rules="rules" :model="pwdform" label-width="100px">
        <el-form-item label="当前密码" prop="password">
          <el-input
            v-if="visible1"
            type="password"
            v-model="pwdform.password"
            placeholder="请输入当前密码"
          >
            <i
              slot="suffix"
              class="el-icon-view el-input__icon"
              title="显示密码"
              @click="changePass1('show')"
              style="cursor:pointer;"
            ></i>
          </el-input>
          <el-input v-else type="text" v-model="pwdform.password" placeholder="请输入当前密码">
            <i
              slot="suffix"
              class="el-icon-more el-input__icon"
              title="隐藏密码"
              @click="changePass1('hide')"
              style="cursor:pointer;"
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="pass">
          <el-input
            v-if="visible2"
            type="password"
            v-model="pwdform.pass"
            :placeholder="`请输入新${pwdPlaceholder}`"
            maxlength="18"
          >
            <i
              slot="suffix"
              class="el-icon-view el-input__icon"
              title="显示密码"
              @click="changePass2('show')"
              style="cursor:pointer;"
            ></i>
          </el-input>
          <el-input
            v-else
            type="text"
            v-model="pwdform.pass"
            :placeholder="`请输入新${pwdPlaceholder}`"
            maxlength="18"
          >
            <i
              slot="suffix"
              class="el-icon-more el-input__icon"
              title="隐藏密码"
              @click="changePass2('hide')"
              style="cursor:pointer;"
            ></i>
          </el-input>
          <div class="pwd_level">
            <div class="level_label">密码安全等级：</div>
            <div class="level_box">
              <div class="level_item" :class="level>=1?'level_item_1':''"></div>
              <div class="level_item" :class="level>=2?'level_item_2':''"></div>
              <div class="level_item" :class="level>=3?'level_item_3':''"></div>
              <div class="level_item" :class="level>=4?'level_item_4':''"></div>
            </div>
            <div class="pwd_tips">（{{pwdPlaceholder}}）</div>
          </div>
        </el-form-item>
        <el-form-item label="确认新密码" prop="checkPass">
          <el-input
            v-if="visible3"
            type="password"
            v-model="pwdform.checkPass"
            placeholder="再次确认新密码"
            maxlength="18"
          >
            <i
              slot="suffix"
              class="el-icon-view el-input__icon"
              title="显示密码"
              @click="changePass3('show')"
              style="cursor:pointer;"
            ></i>
          </el-input>
          <el-input
            v-else
            type="text"
            v-model="pwdform.checkPass"
            placeholder="再次确认新密码"
            maxlength="18"
          >
            <i
              slot="suffix"
              class="el-icon-more el-input__icon"
              title="隐藏密码"
              @click="changePass3('hide')"
              style="cursor:pointer;"
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="submitForm('pwdform')"
            style="width:100px"
          >保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- <div slot="footer" class="dialog-footer">
    </div> -->
  </div>
</template>

<script>
import { putSysUserChangePasswordByBase64 } from '@/api/api.js'
// import { hex_md5 } from '@/utils/md5.js'
import { passwordRegSet, pwdReg } from '@/utils/validate'
import enc from '@/utils/aes'

export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else {
        if (value.length < this.pwdLength) {
          callback(new Error('密码不能低于' + this.pwdLength + '位数'))
        } else if (this.settings.require && (this.pwdReg ? !this.pwdReg.test(value) : !pwdReg(value))) {
          callback(new Error('密码格式不正确'))
        } else if (this.settings.require && this.settings && [... new Set(value)].join('').length < this.settings.requiredUniqueChars) {
          callback(new Error(`密码包含唯一字符的数量不能小于${this.settings.requiredUniqueChars}`))
        } else if (this.pwdform.checkPass !== '') {
          this.$refs.pwdform.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'))
      } else if (value !== this.pwdform.pass) {
        callback(new Error('两次输入新密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      visible1: false,
      visible2: false,
      visible3: false,
      pwdform: {
        password: '',
        pass: '',
        checkPass: ''
      },
      rules: {
        password: [
          { required: true, message: '请输入当前密码', trigger: 'blur' }
        ],
        pass: [
          { required: true, validator: validatePass, trigger: 'blur' },
          { validator: validatePass, trigger: 'change' }
        ],
        checkPass: [
          { required: true, validator: validatePass2, trigger: 'blur' },
          { validator: validatePass2, trigger: 'change' }
        ]
      },
      level: 0,
      pwdReg: '',
      pwdPlaceholder: '',
      pwdLength: '',
      settings: {
        'require': false, // 密码正则验证
        'requireUppercase': true, // 要求大写字母
        'requireLowercase': true, // 要求小写字母
        'requireNonAlphanumeric': true, // 要求非字母数字
        'requireDigit': true, // 要求数字
        'requiredLength': window.g.isClosePassValidate ? 1 : 8, // 密码最小长度
        'requiredUniqueChars': 1 // 唯一字符数量
      }

    }
  },
  watch: {
    'pwdform.pass': function (val, oldVal) {
      this.level = this.AnalyzePasswordSecurityLevel(val)
    }
  },
  created() {
    this.passwordInit()
  },
  methods: {
    passwordInit() {
      if (window.g.PASSWORDSETTINGS) {
        this.settings = window.g.PASSWORDSETTINGS
      }
      this.pwdLength = this.settings.requiredLength
      // 获取密码正则表达式
      this.pwdReg = passwordRegSet(this.pwdLength, this.settings)
      console.log(this.pwdReg)

      // 密码输入提示
      let p = []
      this.settings.requireDigit && p.push('数字')
      if (this.settings.requireUppercase && this.settings.requireLowercase) {
        p.push('大/小写字母')
      } else {
        this.settings.requireUppercase && p.push('大写字母')
        this.settings.requireLowercase && p.push('小写字母')
      }
      this.settings.requireNonAlphanumeric && p.push('特殊字符')
      this.pwdPlaceholder = `密码（${this.pwdLength}-20位），且包含${p.join('、')}`
    },
    submitForm(formName) {
      let that = this
      console.log('submitForm')
      console.log('window.g.isClosePassValidate', window.g.isClosePassValidate)
      if (window.g.isClosePassValidate) {
        that.loading = true
        console.log('that.pwdform.password && that.pwdform.pass && that.pwdform.checkPass', that.pwdform.password && that.pwdform.pass && that.pwdform.checkPass)
        if (that.pwdform.password && that.pwdform.pass && that.pwdform.checkPass) {
          const b = new enc.Base64()
          const params = {
            // oldPassword: that.pwdform.password, //hex_md5(that.pwdform.password).toUpperCase(),
            // newPassword: that.pwdform.pass,//hex_md5(that.pwdform.pass).toUpperCase(),
            // confirmPassword: that.pwdform.checkPass,//hex_md5(that.pwdform.checkPass).toUpperCase()
            oldPassword: b.encode(that.pwdform.password),
            newPassword: b.encode(that.pwdform.pass),
            confirmPassword: b.encode(that.pwdform.checkPass)
          }
          console.log(that.pwdform)
          putSysUserChangePasswordByBase64(params).then((res) => {
            if (res && res.code == 10000) {
              that.$message.success(`${res.message || '密码修改成功！'}`)
              that.pwdform.password = ''
              that.pwdform.pass = ''
              that.pwdform.checkPass = ''
              that.$refs[formName].resetFields()
            }
            that.loading = false
          })
        } else {
          that.$message.success(`密码不可为空！'}`)
        }
      } else {
        this.$refs[formName].validate((valid) => {
          console.log('valid', valid)
          if (valid) {
            that.loading = true
            const b = new enc.Base64()
            const params = {
              // oldPassword: that.pwdform.password, //hex_md5(that.pwdform.password).toUpperCase(),
              // newPassword: that.pwdform.pass,//hex_md5(that.pwdform.pass).toUpperCase(),
              // confirmPassword: that.pwdform.checkPass,//hex_md5(that.pwdform.checkPass).toUpperCase()
              oldPassword: b.encode(that.pwdform.password),
              newPassword: b.encode(that.pwdform.pass),
              confirmPassword: b.encode(that.pwdform.checkPass)
            }
            console.log(that.pwdform)
            putSysUserChangePasswordByBase64(params).then((res) => {
              if (res && res.code == 10000) {
                that.$message.success(`${res.message || '密码修改成功！'}`)
                that.pwdform.password = ''
                that.pwdform.pass = ''
                that.pwdform.checkPass = ''
                that.$refs[formName].resetFields()
              }
              that.loading = false
            })
          } else {
            return false
          }
        })
      }
    },
    AnalyzePasswordSecurityLevel(password) {
      let securityLevelFlag = 0
      if (password.length < 6) {
        return 0
      } else {
        if (/[a-z]/.test(password)) {
          securityLevelFlag++ // lowercase
        }
        if (/[A-Z]/.test(password)) {
          securityLevelFlag++ // uppercase
        }
        if (/[0-9]/.test(password)) {
          securityLevelFlag++ // digital
        }
        if (this.containSpecialChar(password)) {
          securityLevelFlag++ // specialcase
        }
        return securityLevelFlag
      }
    },
    containSpecialChar(str) {
      const containSpecial = RegExp(/[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]+/)
      return (containSpecial.test(str))
    },
    changePass1(value) {
      this.visible1 = !(value === 'show')
    },
    changePass2(value) {
      this.visible2 = !(value === 'show')
    },
    changePass3(value) {
      this.visible3 = !(value === 'show')
    }
  }
}
</script>
<style lang="scss" scoped>
.dialog-footer {
  text-align: center;
  margin-top: 40px;
}
.pwd_level {
  overflow: hidden;
  .level_label {
    float: left;
  }
  .level_box {
    float: left;
    margin-left: 4px;
    .level_item {
      display: inline-block;
      width: 30px;
      height: 8px;
      margin-right: 2px;
      background-color: #ddd;
    }
    .level_item_1 {
      background-color: rgb(255, 8, 0);
    }
    .level_item_2 {
      background-color: rgb(255, 157, 0);
    }
    .level_item_3 {
      background-color: rgb(229, 255, 0);
    }
    .level_item_4 {
      background-color: rgb(60, 255, 0);
    }
  }
  .pwd_tips{
    color: #999;
  }
}
</style>

